package cn.ncu.wechat.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * redis配置类，分别定义RedisTemplate中key和value的数据类型
 * key 是String字符串
 * value 是JSON字符串
 * @author David
 */
//@Configuration
//@EnableCaching //开启SpringCache缓存
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        // 配置连接工厂
        template.setConnectionFactory(factory);

        //设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());

        //设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());

        //设置hash的key序列化方式
        template.setHashKeySerializer(RedisSerializer.string());

        //设置hash的value序列化方式
        template.setHashValueSerializer(RedisSerializer.json());

        //在设置完参数后生效
        template.afterPropertiesSet();

        return template;
    }
}
